package cn.cstech.aijia.ui;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.exception.WeiboException;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.tendcloud.tenddata.TCAgent;

import org.json.JSONObject;

import cn.cstech.aijia.AiJiaApplication;
import cn.cstech.aijia.R;
import cn.cstech.aijia.ui.base.utils.DialogUtil;
import cn.cstech.aijia.sns.Constants;
import cn.cstech.aijia.ui.base.BaseActivity;
import cn.cstech.aijia.ui.base.utils.LoadingDialog;
import cn.cstech.aijia.ui.base.utils.LocalUtils;
import cn.cstech.aijia.ui.base.utils.SPUtils;
import cn.cstech.aijia.ui.base.views.LoginButton;

/**
 * Created with Android Studio.
 * Title:BaseActivity
 * Description:
 * Copyright:Copyright (c) 2014
 * Company:中国平安健康保险有限公司
 * Author:Alice
 * Date:15/8/28
 * Time:下午4:22
 * Version 1.0
 */
public class BaseLoginActivity extends BaseActivity{
    private static final int MSG_TIMER = 1;
    private static final int MSG_LOGIN_OK = 0x1001;
    private static final int MSG_LOGIN_KO = 0x1002;
    private static final int MSG_SHOW_TOAST = 0x1003;
    private static final int MSG_USER_EXISTED = 0x1004;
    private static final int MSG_VERIFY_FAILD = 0x1005;
    private static final int MSG_VERIFY_OK = 0x10031;
    private static final int MSG_RETRY = 0x1008;
    private static final int MSG_REGISTER_OK = 0x1006;
    private static final int MSG_ALREADY_REGISTER = 0x1007;

    private static final int MSG_REGISTER_REAL = 0x1009;
    private static final int MSG_SHOW_PROMOTION = 0x10010;

    private Context context;
    private EditText mPhoneNumberEditText;
    private IWXAPI mWXApi;
    private LinearLayout mTitlebar;
    /** @Fields verifyCodeEt: 验证码输入框*/
    private EditText mVerifyCodeEt;
    private boolean isDeviceTrust = true;
    private boolean isOpEnd = true;
    /** @Fields mSendReqcodeBtn: 请求短信按钮*/
    private TextView mSendReqcodeBtn;
    /** @Fields mLoginBtn: 登录按钮*/
    private Button mLoginBtn;
    //微信登陆的按钮
    private Button mWeixinLoginBtn;
    /** @Fields phoneNumber: 填写的手机号码  -- 临时点击时的手机号码*/
    private String phoneNumber;
    private String mAskedPhoneNumber;
    private boolean mHasSendCode = false;
    /** @Fields isRequestungDynamicCode: 是否已经正在请求验证码*/
    boolean isRequestungDynamicCode = false;
    /** @Fields isVerifyCodeTime: 是否在60秒时间内*/
    private boolean isVerifyCodeTime = false;
    private String mSmsContent;
    public static Tencent mTencent;
    private AuthInfo mAuthInfo;
    /** 登陆认证对应的listener */
    private AuthListener mLoginListener = new AuthListener();

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        context = this;

        initQQ();
        initWeiBo();
        initWXAPI();

        setContentView(R.layout.sample_login_activity);

        setTitle("登录");
        initUI();

        ((AiJiaApplication) getApplication()).addActivity(this);

        registerReceiver(ConnectionChangeReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    }
    /****************************************QQ BEGIN************************************/
    private void initQQ(){
        if (mTencent == null) {
            mTencent = Tencent.createInstance(Constants.QQ_APP_ID, this);
        }
    }

    IUiListener mQQLoginListener = new BaseUiListener() {
        @Override
        protected void doComplete(JSONObject values) {
            LocalUtils.showToast(BaseLoginActivity.this, R.string.toast_qq_login_success);
            initOpenidAndToken(values);
        }
    };


    private void doQQLogin(String accessToken){
        showLoadingDialog("");
//        NetManager.getInstance(this).doQqLogin(accessToken, new OnResponseListener<Boolean>() {
//
//            @Override
//            public void onInernError(int errorCode, String errorMessage) {
//                hideLoadingDialog();
//                LocalUtils.showToast(LoginActivity.this, errorMessage);
//            }
//
//            @Override
//            public void onComplete(boolean isOK, Boolean result, int errorCode,
//                                   String errorMsg) {
//                if(isOK && result){
//                    gotoMain();
//                }else{
//                    hideLoadingDialog();
//                    LocalUtils.showToast(LoginActivity.this, StringUtil.handlerErrorCode(LoginActivity.this, errorCode));
//                }
//            }
//        });
    }

    private void initOpenidAndToken(JSONObject jsonObject) {
        try {
            String token = jsonObject.getString(com.tencent.connect.common.Constants.PARAM_ACCESS_TOKEN);
            doQQLogin(token);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    private class BaseUiListener implements IUiListener {

        @Override
        public void onComplete(Object response) {
            if (null == response) {
                LocalUtils.showToast(BaseLoginActivity.this,R.string.toast_qq_login_failed);
                return;
            }
            JSONObject jsonResponse = (JSONObject) response;
            if (null != jsonResponse && jsonResponse.length() == 0) {
                LocalUtils.showToast(BaseLoginActivity.this,R.string.toast_qq_login_failed);
                return;
            }

            doComplete((JSONObject)response);
        }

        protected void doComplete(JSONObject values) {

        }

        @Override
        public void onError(UiError e) {
        }

        @Override
        public void onCancel() {
        }
    }

    private void gotoMain(){
        isOpEnd = true;
        Message.obtain(mUIHandler, MSG_LOGIN_OK).sendToTarget();
    }
    /****************************************QQ END************************************/

    /****************************************WeiBo BEGIN************************************/
    //TODO
    LoginButton login_weibo_btn;
    Button login_qq_btn;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(login_weibo_btn != null){
            login_weibo_btn.onActivityResult(requestCode, resultCode, data);
        }
    }

    private void initWeiBo(){
        // 创建授权认证信息
        mAuthInfo = new AuthInfo(this, Constants.WEIBO_APP_ID, Constants.REDIRECT_URL, Constants.SCOPE);
    }

    /**
     * 登入按钮的监听器，接收授权结果。
     */
    private class AuthListener implements WeiboAuthListener {
        @Override
        public void onComplete(Bundle values) {
            Oauth2AccessToken accessToken = Oauth2AccessToken.parseAccessToken(values);
            if (accessToken != null && accessToken.isSessionValid()) {
                doWeiBoLogin(accessToken.getToken());
                LocalUtils.showToast(BaseLoginActivity.this,R.string.toast_weibo_login_success);
            }else{
                LocalUtils.showToast(BaseLoginActivity.this,R.string.toast_weibo_login_failed);
            }
        }

        @Override
        public void onWeiboException(WeiboException e) {
            LocalUtils.showToast(BaseLoginActivity.this, e.getMessage());
        }

        @Override
        public void onCancel() {
            LocalUtils.showToast(BaseLoginActivity.this, android.R.string.cancel);
        }
    }

    private void doWeiBoLogin(String accessToken){
        showLoadingDialog("");
//        NetManager.getInstance(this).doWeiBoLogin(accessToken, new OnResponseListener<Boolean>() {
//
//            @Override
//            public void onInernError(int errorCode, String errorMessage) {
//                hideLoadingDialog();
//                LocalUtils.showToast(LoginActivity.this, errorMessage);
//            }
//
//            @Override
//            public void onComplete(boolean isOK, Boolean result, int errorCode,
//                                   String errorMsg) {
//                if(isOK && result){
//                    gotoMain();
//                }else{
//                    hideLoadingDialog();
//                    LocalUtils.showToast(LoginActivity.this, StringUtil.handlerErrorCode(LoginActivity.this, errorCode));
//                }
//            }
//        });
    }
    //TODO
    /****************************************WeiBo END************************************/
    @Override
    protected void onResume() {
        String lastPhoneNumber = getLastPhoneNumber();
        if (lastPhoneNumber != null && mPhoneNumberEditText != null) {
            mPhoneNumberEditText.setText(getLastPhoneNumber());
        }

        if(mTencent != null && mTencent.isSupportSSOLogin(this)){
            login_qq_btn.setVisibility(View.VISIBLE);
        }else{
            login_qq_btn.setVisibility(View.GONE);
        }

        if(mWXApi != null && mWXApi.isWXAppInstalled()){
            mWeixinLoginBtn.setVisibility(View.VISIBLE);
        }else{
            mWeixinLoginBtn.setVisibility(View.GONE);
        }

        super.onResume();
        TCAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        TCAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        if(ConnectionChangeReceiver != null){
            unregisterReceiver(ConnectionChangeReceiver);
        }
        super.onDestroy();
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.right_in, R.anim.left_out);
    }

    private void initUI() {
        mPhoneNumberEditText = (EditText) findViewById(R.id.phone_number_edit);
        mPhoneNumberEditText
                .setOnEditorActionListener(new TextView.OnEditorActionListener() {
                    @Override
                    public boolean onEditorAction(TextView v, int actionId,
                                                  KeyEvent event) {
                        if (actionId == EditorInfo.IME_ACTION_DONE
                                || actionId == EditorInfo.IME_ACTION_SEND
                                || actionId == EditorInfo.IME_ACTION_GO
                                || actionId == EditorInfo.IME_ACTION_SEARCH
                                || actionId == EditorInfo.IME_ACTION_NEXT
                                || actionId == EditorInfo.IME_ACTION_PREVIOUS) {
                            reqSmsCode();
                            return true;
                        }
                        return false;
                    }
                });

        //重新发送按钮
        mSendReqcodeBtn = (TextView) findViewById(R.id.send_reqcode_btn);
        mSendReqcodeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                reqSmsCode();
            }
        });

        mVerifyCodeEt = (EditText)findViewById(R.id.verify_code_et);
        mVerifyCodeEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_SEND
                        || actionId == EditorInfo.IME_ACTION_GO) {

                    onFinishClick();
                    return true;
                }
                return false;
            }
        });

        mLoginBtn = (Button) findViewById(R.id.login_btn);
        mLoginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onFinishClick();
            }
        });

        mWeixinLoginBtn = (Button) findViewById(R.id.login_weixin_btn);
        mWeixinLoginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doLoginByWeiXin();
            }
        });
        //微博登陆
        login_weibo_btn = (LoginButton) findViewById(R.id.login_weibo_btn);
        login_weibo_btn.setWeiboAuthInfo(mAuthInfo, mLoginListener);
        login_weibo_btn.setExternalOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                }
        });

        //QQ登陆
        login_qq_btn = (Button) findViewById(R.id.login_qq_btn);
        login_qq_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doLoginQQ();
            }
        });

        mPhoneNumberEditText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                showLoginButton();
                showSendReqButton();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        mVerifyCodeEt.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                showLoginButton();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        TextView tv_app_protocal = (TextView) findViewById(R.id.tv_app_protocal);
        tv_app_protocal.setText(Html
                .fromHtml(getString(R.string.label_protocal_hint_new)));
        tv_app_protocal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO go to protocal page
//                UserCenterUtil.jumpToAppProtocalPage(LoginActivity.this);
            }
        });

        showLoginButton();
        showSendReqButton();
    }

    /**
     * QQ登录
     */
    private void doLoginQQ(){
        if (mTencent != null && mTencent.isSessionValid()) {
            // TODO 已经登录
//			mTencent.logout(this);
            doQQLogin(mTencent.getAccessToken());
        } else {
            // TODO 未登录
            mTencent.login(this, "all", mQQLoginListener);
        }
    }


    private void doLoginByWeiXin(){
        if(!isSupported()){
            showErrorMsg(R.string.weixin_not_installed);
//			LocalUtils.showCenterToast(LoginActivity.this, R.string.weixin_not_installed);
        }else{
            doLoginWeixin();
        }
    }

    public void initWXAPI(){
        mWXApi = WXAPIFactory.createWXAPI(context, Constants.WEIXIN_APP_ID, false);
        registerToWX();
    }

    private void registerToWX(){
        mWXApi.registerApp(Constants.WEIXIN_APP_ID);
    }

    public boolean isSupported(){
        return mWXApi.isWXAppInstalled() && mWXApi.isWXAppSupportAPI();
    }

    /**
     * 登录微信
     */
    private void doLoginWeixin() {
        final SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "sns_userlogin";
        mWXApi.sendReq(req);
    }

    private String getLastPhoneNumber() {
        return SPUtils.getMobilePhone(this);
    }

    /**
     * @Description 判断手机号码----再进行请求验证码
     * @author xiezhidong251@jk.cn
     * @return
     */

    private boolean reqSmsCode() {
        phoneNumber = mPhoneNumberEditText.getText().toString();
        if(phoneNumber.trim().length() < 1){
            showErrorMsg(getString(R.string.phone_number_null));
            return false;
        }
        if (LocalUtils.isMobileNO(phoneNumber)) {
            if (phoneNumber.startsWith("11") || phoneNumber.startsWith("12")
                    || phoneNumber.startsWith("19")) {
                showErrorMsg(getString(R.string.label_not_support_number));
            }else{
//				showPhoneNumberConfirmDialog();
                doGetDynamicCode();
            }
        } else {
            showErrorMsg(getString(R.string.label_invalid_phonenumber));
        }
        return true;
    }

    /**
     * @Description 请求短信
     * @author xiezhidong251@jk.cn
     */

    private void doGetDynamicCode() {
        if(isRequestungDynamicCode){
            showErrorMsg(R.string.toast_try_too_much);
            return ;
        }
        isRequestungDynamicCode = true;
        changeInputMethod();
        mAskedPhoneNumber = phoneNumber;
        mHasSendCode = false;
//        NetManager.getInstance(context).doRequestDynamic(phoneNumber, Preference.USAGE_LOGIN, new OnRequestDynamicListener() {
//            @Override
//            public void onComplete(boolean b, String s, String s2, int i, String s3) {
//                hideLoadingDialog();
//                isRequestungDynamicCode = false;
//                if (b) {
//                    mHasSendCode = true;
//                    showLoginButton();
//                    mSmsContent = s2;
//                    mUpstreamSmsPhoneNumber = s;
//                    Trace.i("send msg success:" + s2);
//                    //显示消息已发送提示
//                    Message.obtain(mHandler,MSG_SHOW_TOAST,getString(R.string.verify_code_has_send_string)).sendToTarget();
//                    LoginActivity.this.runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            mHandler.removeMessages(MSG_TIMER);
//                            startCounter();
//                        }
//                    });
//                } else {
//                    Trace.i("send msg fail:" + s3);
//                    Message.obtain(mHandler, MSG_SHOW_TOAST,StringUtil.handlerErrorCode(getApplication(), i)).sendToTarget();
//                }
//            }
//
//            @Override
//            public void onInernError(int errorCode, final String errorMessage) {
//                hideLoadingDialog();
//                isRequestungDynamicCode = false;
//                Message.obtain(mHandler,MSG_SHOW_TOAST,StringUtil.handlerErrorCode(context, errorCode)).sendToTarget();
//            }
//        });
    }


    /**
     * @Description 设置60秒倒计时
     * @author xiezhidong251@jk.cn
     */

    private void startCounter() {
        isVerifyCodeTime = true;
        mSendReqcodeBtn.setEnabled(false);
        mSendReqcodeBtn.setBackgroundResource(R.drawable.login_btn_code);
        mSendReqcodeBtn.setPadding(24, 0, 24, 0);
        mSendReqcodeBtn.setTextColor(Color.GRAY);
        setVerifyCodeTime(60);
        sendTime(60);
    }

    private void showSendReqButton(){
        if(isVerifyCodeTime){
            return;
        }
        if(TextUtils.isEmpty(mPhoneNumberEditText.getText().toString())){
            mSendReqcodeBtn.setEnabled(false);
            mSendReqcodeBtn.setBackgroundResource(R.drawable.login_btn_code);
            mSendReqcodeBtn.setPadding(24, 0, 24, 0);
            mSendReqcodeBtn.setTextColor(Color.GRAY);
        } else {
            mSendReqcodeBtn.setEnabled(true);
            mSendReqcodeBtn.setBackgroundResource(R.drawable.login_btn_code_blue);
            mSendReqcodeBtn.setTextColor(getResources().getColor(R.color.config_color_m2));
            mSendReqcodeBtn.setPadding(24, 0, 24, 0);
        }
    }

    private void showLoginButton(){
        if(mHasSendCode
                && !TextUtils.isEmpty(mPhoneNumberEditText.getText().toString())
                && !TextUtils.isEmpty(mVerifyCodeEt.getText().toString())) {
            mLoginBtn.setClickable(true);
            mLoginBtn.setEnabled(true);
            mLoginBtn.setPressed(true);
            mLoginBtn.setBackgroundResource(R.drawable.login_btn_blue_drawable);
        } else {
            mLoginBtn.setClickable(false);
            mLoginBtn.setEnabled(false);
            mLoginBtn.setPressed(false);
            mLoginBtn.setBackgroundResource(R.drawable.login_btn_gray_drawable);
        }
    }


    private void setVerifyCodeTime(int seconds) {
        if (seconds == 0) {
            mSendReqcodeBtn.setText(getString(R.string.req_dynamic_code));
            isVerifyCodeTime = false;
            return;
        }
        String time = String.format(getString(R.string.vefity_code_timer), seconds);
        mSendReqcodeBtn.setText(time);
    }

    private void sendTime(int seconds) {
        Message msg = mUIHandler.obtainMessage(MSG_TIMER, seconds, 0);
        mUIHandler.sendMessageDelayed(msg, 1000);
    }

    private LoadingDialog loadingDialog;
    protected void showLoadingDialog(String msg) {
        if (loadingDialog == null) {
            loadingDialog = DialogUtil.showLoadingDialog(this, msg, true);
        }
        if (!TextUtils.isEmpty(msg)) {
            loadingDialog.setDlgMessage(msg);
        }
        if (!loadingDialog.isShowing()) {
            loadingDialog.show();
        }
    }

    protected void hideLoadingDialog() {
        if (!isFinishing() && loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_LOGIN_OK:
                hideLoadingDialog();
                showToast(context, getString(R.string.login_success));
                break;
            case MSG_LOGIN_KO:
                hideLoadingDialog();
                showErrorMsg((String) msg.obj);
                break;
            case MSG_SHOW_TOAST:
                hideLoadingDialog();
                showToast(context, (String) msg.obj);
                break;
            case MSG_REGISTER_OK:
                SPUtils.setMobilePhone(context, phoneNumber);
                showToast(context, getString(R.string.register_success));
                ((AiJiaApplication)getApplication()).exitAllActivity();
//                if(!TextUtils.isEmpty(mEnterAppAction)){
//                    Intent intent = new Intent(mEnterAppAction);
//                    intent.putExtra(Preference.EXTRA_FROM, Preference.FROM_REGISTER);
//                    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                    startActivity(intent);
//                }
                finish();
                break;
            case MSG_RETRY:
                processAction();
                break;
            case MSG_TIMER:
                if (msg.arg1 > 0) {
                    setVerifyCodeTime(msg.arg1-1);
                    sendTime(msg.arg1-1);
                } else {
                    setVerifyCodeTime(0);
                    mSendReqcodeBtn.setEnabled(true);
                    showSendReqButton();
                    mSendReqcodeBtn.setTextColor(getResources().getColor(R.color.config_color_m2));
                }
                break;
            case MSG_ALREADY_REGISTER:
                showAlreadyRegisterDialog();
                break;
            case MSG_USER_EXISTED:
                checkRegisterSecurity();
                break;
            case MSG_VERIFY_FAILD:
                isOpEnd = true;
                hideLoadingDialog();
                showErrorMsg(R.string.toast_query_sms_failed);
//        	LocalUtils.showToast(this, R.string.toast_query_sms_failed);
                break;
            case MSG_VERIFY_OK:
                hideLoadingDialog();
                break;
            case MSG_REGISTER_REAL:
                doRegisterReal();
                break;
        }
    }

    private void showToast(Context context, String obj) {
        showLocalToast(obj);
    }

    private void showErrorMsg(String msg) {
        Message.obtain(mUIHandler,MSG_SHOW_TOAST, msg).sendToTarget();
    }

    private void showErrorMsg(int resId) {
        Message.obtain(mUIHandler,MSG_SHOW_TOAST, getString(resId)).sendToTarget();
    }
    private BroadcastReceiver ConnectionChangeReceiver = new BroadcastReceiver(){

        @Override
        public void onReceive(Context arg0, Intent arg1) {
            if(arg0 == null){
                return;
            }

            if(arg1 == null){
                return;
            }

            if(arg1.getAction() == ConnectivityManager.CONNECTIVITY_ACTION){
                ConnectivityManager connectivityManager = (ConnectivityManager)BaseLoginActivity.this
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo activeNetInfo = connectivityManager
                        .getActiveNetworkInfo();
                if (activeNetInfo != null && activeNetInfo.isAvailable()) {
//                    if(SharedPreferenceUtil.getDeviceToken(BaseLoginActivity.this) == null){
//                        UserCenterUtil.registerDevice(BaseLoginActivity.this);
//                    }
                }
            }
        }
    };

    private void doRegisterReal() {
        showLoadingDialog(getString(R.string.dlg_msg_registing));
        dynamicCode = mVerifyCodeEt.getText().toString();
//        NetManager.getInstance(context).doUserReister(phoneNumber, dynamicCode, false, new OnUserRegisterListener() {
//            @Override
//            public void onComplete(boolean b, int i, String s) {
//                hideLoadingDialog();
//                Trace.i("register result:"+ b +"  "+i + "  s:"+s);
//                if (b) {
//                    isUpSmsStarted = false;
//                    isOpEnd = true;
//                    isNeedWaiting = false;
//                    Message.obtain(mHandler, MSG_REGISTER_OK).sendToTarget();
//                } else {
//                    if(i == ApiCode.UPLINK_SMS_NOT_RECEIVED){
//                        isNeedWaiting = true;
//                    }else if(i == ApiCode.USER_EXIST_1003040){
//                        //TODO 用户已存在
//                        isNeedWaiting = false;
//                        Message.obtain(mHandler, MSG_USER_EXISTED).sendToTarget();
//                    }else{
//                        isNeedWaiting = false;
//                        if(i == ApiCode.DYNAMIC_CODE_ERROR){
//                            showErrorMsg(R.string.verify_code_error);
////                			showVerifyCodeErrorDialog(getString(R.string.verify_code_error));
//                        }else{
//                            Message.obtain(mHandler,MSG_SHOW_TOAST,StringUtil.handlerErrorCode(LoginActivity.this, i)).sendToTarget();
//                        }
//                    }
//                }
//            }
//
//            @Override
//            public void onInernError(int errorCode, final String errorMessage) {
//                hideLoadingDialog();
//                isNeedWaiting = false;
//                Message.obtain(mHandler,MSG_SHOW_TOAST,StringUtil.handlerErrorCode(context, errorCode)).sendToTarget();
//            }
//        });
    }

    /**
     * 注册时候检查是否为可信设备
     */
    String dynamicCode;
    private void checkRegisterSecurity() {
        dynamicCode = mVerifyCodeEt.getText().toString().trim();
        if(dynamicCode.length() < 1){
            dynamicCode = mSmsContent;
        }

        mUIHandler.sendEmptyMessage(MSG_ALREADY_REGISTER);
    }

    // Dialog AlreadyRegisterDlg;
    private void showAlreadyRegisterDialog() {
        new AlertDialog.Builder(this).setMessage(getString(R.string.already_register))
                .setPositiveButton(getString(R.string.login_now), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (isDeviceTrust) {
                            login();
                        }
                    }
                }).setNegativeButton(getString(R.string.label_btn_cancel), null).show();
    }


    private void onFinishClick(){
        if( mVerifyCodeEt.getText().toString().trim().length() < 1){
            showErrorMsg(R.string.hint_inout_verify_code);
            return ;
        }
        if (!isVerifyCodeRight()) {
            showErrorMsg(R.string.verify_code_error);
            return;
        }

//		Map<String,Object> kv = new HashMap<String,Object>();
//		kv.put("入口", "输入短信验证码页面");
//    	TCAgent.onEvent(LoginActivity.this, com.pajk.usercenter.datacenter.Constants.BUTTON_LOGIN_CLICK, null, kv);

        processAction();
    }

    /**
     * @Description 按照验证码请求的状态进行跳转
     * @author xiezhidong251@jk.cn
     */

    private void processAction() {
//        if (mAction == null) {
//            return;
//        }
//        if (mAction.equals(Preference.ACTION_FIND_PWD)) {
//            // checkSecurity();
//        } else if (mAction.equals(Preference.ACTION_REGISTER)) {
////			doRegisterReal();
//        } else if (mAction.equals(Preference.ACTION_LOGIN_BY_SMSPWD)) {
//            login();
//        }
    }

    private void login(){
        if(!mHasSendCode){
            Message.obtain(mUIHandler,MSG_SHOW_TOAST, getString(R.string.dlg_msg_requesting_dynamic)).sendToTarget();
            return;
        }

        if(!mAskedPhoneNumber.equals(mPhoneNumberEditText.getText().toString())){
            Message.obtain(mUIHandler,MSG_SHOW_TOAST, getString(R.string.login_phone_changed)).sendToTarget();
            return;
        }

        doLogin();
    }

    /**
     * @Description 登录
     * @author xiezhidong251@jk.cn
     */

    private void doLogin() {
        showLoadingDialog(getString(R.string.dlg_msg_logining));
        dynamicCode = mVerifyCodeEt.getText().toString();
//        NetManager.getInstance(context).doLoginByPassword(mAskedPhoneNumber, dynamicCode, new OnLoginByPasswordListener() {
//            @Override
//            public void onComplete(boolean b, int i, String s) {
//                hideLoadingDialog();
//                Trace.i("login result:"+b);
//                if (b) {
//                    isUpSmsStarted = false;
//                    isOpEnd = true;
//                    isNeedWaiting = false;
//                    Message.obtain(mHandler, MSG_LOGIN_OK).sendToTarget();
//                } else {
//                    if(i == ApiCode.NO_TRUSTED_DEVICE){
//                        //TODO 非授信设备
//                        isNeedWaiting = false;
////                		Intent intent = new Intent(context, CheckSafeQuestionActivity.class);
////                      intent.putExtra(Preference.ACTION, Preference.ACTION_LOGIN);
////                      intent.putExtra(Preference.PHONE_NUMBER, mAskedPhoneNumber);
////                      intent.putExtra(Preference.DYNAMIC_CODE, dynamicCode);
////                      context.startActivity(intent);
//                    }else if(i == ApiCode.MOBILE_NOT_REGIST){
////                		showNoRegisterDialog();
////                		doRegisterReal();
//                        SDOAnalyzeAgentInterface
//                                .onEvent(
//                                        context,
//                                        com.pajk.usercenter.datacenter.Constants.BUTTON_SIGN_CLICK);
//                        TCAgent.onEvent(LoginActivity.this, com.pajk.usercenter.datacenter.Constants.BUTTON_SIGN_CLICK);
//
//                        Message.obtain(mHandler, MSG_REGISTER_REAL).sendToTarget();
//                    }else if(i == ApiCode.USER_LOCKED){
//                        ContextHelper.gotoBlackHouse(LoginActivity.this, Long.parseLong(s));
//                    }else {
//                        if(i == ApiCode.UPLINK_SMS_NOT_RECEIVED){
//                            isNeedWaiting = true;
//                        }else{
//                            isNeedWaiting = false;
//                            if(i == ApiCode.DYNAMIC_CODE_ERROR){
//                                showErrorMsg(R.string.verify_code_error);
////                    			showVerifyCodeErrorDialog(getString(R.string.verify_code_error));
//                            }else{
//                                Message.obtain(mHandler,MSG_SHOW_TOAST,StringUtil.handlerErrorCode(context, i)).sendToTarget();
//                            }
//                        }
//                    }
//                }
//            }
//
//            @Override
//            public void onInernError(int errorCode, final String errorMessage) {
//                hideLoadingDialog();
//                isNeedWaiting = false;
//                Message.obtain(mHandler,MSG_SHOW_TOAST,StringUtil.handlerErrorCode(context, errorCode)).sendToTarget();
//            }
//        });
    }

    /**
     * @Description 判断是否为6位验证码
     * @author xiezhidong251@jk.cn
     * @return
     */

    private boolean isVerifyCodeRight() {
        return mVerifyCodeEt.getText().toString().matches("\\d{6}");
    }

    private void showLocalToast(String msg) {
        Toast toast = Toast.makeText(context, msg, Toast.LENGTH_LONG);
        int i = mTitlebar.getHeight();
        toast.setGravity(Gravity.TOP, toast.getXOffset()/2, i);
        toast.show();

    }

    /**
     * @Description 切换键盘
     * @author xiezhidong251@jk.cn
     */

    private void changeInputMethod() {
        mVerifyCodeEt.requestFocus();
    }

}
